import { useState, useEffect } from "react";
export const isFalsy = (value: unknown) => (value === 0 ? false : !value);

// 在一个函数里，改变传入的对象本身是不好的
// 如果一个函数里没有用到hooks，那么就不用封装成custom hooks
export const cleanObject = (object: object) => {
  const result = { ...object };
  Object.keys(object).forEach((key) => {
    // @ts-ignore
    const value = object[key];
    if (isFalsy(value)) {
      // @ts-ignore
      delete result[key];
    }
  });
  console.log("result", result);
  return result;
};

export const useMount = (cb: () => void) => {
  useEffect(() => {
    cb && cb();
  }, []);
};

// 后面用泛型来规范类型
export const useDebounce = <V>(value: V, delay?: number) => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    // return是在上一次useEffect处理完之后在运行
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
};
